<template>
  <BasicTable @register="registerTable">
    <template #tableTitle>
      <a-button
        type="primary"
        v-if="canWrite"
        preIcon="ant-design:plus-outlined"
        @click="handleCreate">
        新增菜单
      </a-button>
      <a-button type="primary" preIcon="ant-design:import-outlined" @click="handleImportMenu">
        导入菜单
      </a-button>
      <a-button type="primary" preIcon="ic:round-expand" @click="expandAll">
        展开全部
      </a-button>
      <a-button type="primary" preIcon="ic:round-compress" @click="collapseAll">
        折叠全部
      </a-button>
    </template>
    <template #firstColumn="{ record }">
      <Icon
        :icon="record.icon || 'i-ant-design:file-outlined'"
        @click="expandCollapse(record)"
        class="mr-2 w-5 text-base"
      />
      <a @click="handleEdit(record)" :title="record.name">
        {{ record.name }}
      </a>
    </template>
    <template #apiActions="{ record }">
      <div v-if="record.apiActions?.length > 0">
        <Tooltip placement="top">
          <template #title>
            <span v-for="item in record.apiActions" :key="item"> {{ item }} <br /> </span>
          </template>
          <a-button type="link">查看</a-button>
        </Tooltip>
      </div>
    </template>
    <template #action="{ record }">
      <TableAction
        :actions="getTableAction(record)"
        :dropDownActions="getDropDownAction(record)"
      />
    </template>
  </BasicTable>
  <MenuDrawer
    @register="registerDrawer"
    @success="handleSuccess"
    :showFooter="showFooter"
  />
  <ImportMenu @register="registerImportMenu" @success="reload" />
</template>
<script lang="ts" name="system-menu" setup>
import { nextTick, unref, ref, onMounted } from "vue";
import { Tooltip } from "ant-design-vue";
import { BasicTable, useTable, TableAction } from "/@/components/Table";
import { useListPage } from "/@/hooks/system/useListPage";
import { useDrawer } from "/@/components/Drawer";
import { useCopyToClipboard } from "/@/hooks/web/useCopyToClipboard";
import MenuDrawer from "./components/MenuDrawer.vue";
import ImportMenu from "./components/ImportMenu.vue";
import { columns, searchFormSchema } from "./data";
import * as menuApi from "/@/api/iam/menu";
import { useRouter } from "vue-router";
import { useMessage } from "/@/hooks/web/useMessage";
import { Icon } from "/@/components/Icon";
import { useUserStore } from "/@/store/modules/user";
const { clipboardRef, copiedRef } = useCopyToClipboard();
const userStore = useUserStore();
const selectTenant = userStore.getSelectTenant;
const { createMessage } = useMessage();
const router = useRouter();
let appId = router.currentRoute.value.query?.appId;

const props = defineProps({
  apiNamespaceCode: { type: String },
});

const checkedKeys = ref<Array<string | number>>([]);
const showFooter = ref(true);
const canWrite = ref(true);
// const hasShowSceneAuth = computed(() => selectTenant?.tenantType == TenantType.PLATFORM)
const [registerDrawer, { openDrawer }] = useDrawer();
const [registerImportMenu, { openDrawer: openImportMenu }] = useDrawer();

const { prefixCls, tableContext } = useListPage({
  tableProps: {
    title: "菜单列表",
    api: menuApi.listMenu,
    immediate: false,
    beforeFetch: (params) => {
      params.appId = appId;
      params.apiNamespaceCode = props.apiNamespaceCode;
    },
    afterFetch: (data) => {
      console.log("data", data);
      if (!props.apiNamespaceCode) {
        return;
      }
      // todo sgy 后续优化
      canWrite.value = data?.length > 0 ? data[0].canWrite : true;
    },
    formConfig: {
      labelWidth: 90,
      schemas: searchFormSchema,
    },
    columns: columns,
    size: "small",
    pagination: false,
    isTreeTable: true,
    striped: true,
    useSearchForm: true,
    showTableSetting: true,
    bordered: false,
    showIndexColumn: false,
    tableSetting: { fullScreen: true },
    actionColumn: {
      width: 200,
      title: "操作",
      dataIndex: "action",
      fixed: "right",
      slots: { customRender: "action" },
    },
  },
});

const [registerTable, { reload, getForm, expandAll, collapseAll, expandCollapse }] = tableContext;

onMounted(() => {
  const { updateSchema, setFieldsValue } = getForm();
  reload();
});

function handleCreate() {
  console.time("menu-drawer");
  showFooter.value = true;
  openDrawer(true, {
    isUpdate: false,
    appId,
    apiNamespaceCode: props.apiNamespaceCode,
  });
}

function handleEdit(record) {
  console.time("menu-drawer");
  showFooter.value = true;

  openDrawer(true, {
    record,
    appId,
    apiNamespaceCode: props.apiNamespaceCode,
    isUpdate: true,
  });
}

function handleAddSub(record) {
  openDrawer(true, {
    record: { parentId: record.id, menuType: "1" },
    appId,
    apiNamespaceCode: props.apiNamespaceCode,
    isUpdate: false,
  });
}

async function handleDelete(record) {
  await menuApi.deleteMenu(
    { id: record.id, apiNamespaceCode: props.apiNamespaceCode },
    reload
  );
}

async function handleImportMenu(record) {
  openImportMenu(true, { parentId: record?.id });
}

async function handleCopyMenu(record) {
  clipboardRef.value = "";
  createMessage.loading({
    content: "复制中...",
    key: "loading",
    duration: 0
  });

  try {
    const data = await menuApi.getCopyMenu({ parentId: record.id });
    clipboardRef.value = JSON.stringify(data, null, 2);
    if (unref(copiedRef)) {
      createMessage.success(`所选菜单【${record.name}】以及子菜单已保存到剪切板`);
    } else {
      createMessage.success("复制失败");
    }
  } finally {
    createMessage.destroy("loading");
  }
}

function handleSuccess() {
  reload();
}

function onFetchSuccess() {
  // 演示默认展开所有表项
  nextTick(expandAll);
}

async function handleUpdateStatus(record, status) {
  await menuApi.updateMenuStatus({ id: record.id, namespaceCode: record.namespaceCode, status })
  createMessage.success("更新成功")
  await reload()
}

function getTableAction(record) {
  return [
    {
      label: "编辑",
      ifShow: canWrite.value,
      onClick: handleEdit.bind(null, record),
    },
    {
      label: "删除",
      color: "error",
      disabled: !canWrite.value || record.addonId,
      popConfirm: {
        title: `是否确认删除 ${record.name}`,
        confirm: handleDelete.bind(null, record),
      },
    },
    {
      label: "禁用",
      color: "error",
      ifShow: record.status == 1,
      // auth: 'sys:area:updateStatus',
      popConfirm: {
        title: "确定禁用吗?",
        confirm: handleUpdateStatus.bind(null, record, 2),
      },
    },
    {
      label: "启用",
      ifShow: record.status == 2,
      popConfirm: {
        title: "确定启用吗?",
        confirm: handleUpdateStatus.bind(null, record, 1),
      },
    }
  ];
}

function getDropDownAction(record) {
  return [
    {
      label: "复制",
      ifShow: canWrite.value && !record.addonId,
      onClick: handleCopyMenu.bind(null, record),
    },
    {
      label: "导入子级",
      ifShow: canWrite.value && !record.addonId,
      onClick: handleImportMenu.bind(null, record),
    },
    {
      label: "添加下级",
      ifShow: canWrite.value && !record.addonId,
      onClick: handleAddSub.bind(null, record),
    }
  ];
}
</script>
